package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.cloudbroker.bcs.common.context.DataContext;
import com.cloudbroker.bcs.common.entity.HSBCPSBackNumVO;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.model.Pagination;
import com.cloudbroker.bcs.common.model.SortMarker;
import com.cloudbroker.bcs.common.util.DateTimeUtil;
import com.cloudbroker.bcs.common.util.EnumUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ChatRoomErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSFields;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.PaySource;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.ChatType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.GagType;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.ChatBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.CCRoomOperResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.ChatMsgListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.ChatMsgPageResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.ChatTopicListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.ChatTopicListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.LiveBroadcastUrlDetailResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.SchemeColorValueResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.TenantInfoResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.BrokerInfoBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.BrokerInfoNologinBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.BrokerInfoNologinForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.CCRoomInfoFrom;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.CCRoomOperInfoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.CCRoomStatusForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.ChatHisBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.ChatRoomInfoBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.ChatRoomSetForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.ChatTopicForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.ChatTopicListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.GetCacheChatMsgForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.GetHisChatMsgForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.HisChatDelForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.LiveBroadcastUrlForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.RewardNumBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.SchemeColorSelectForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.SetHisChatForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.TenantKeyForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.UserBlockForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.UserGagForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.GetTicketForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.SetMemberRoleForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.GetTicketBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.SetMemberRoleBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.CCLiveT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.WeixinT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.YunxinT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.CacheKeys;
import com.cloudbroker.bcs.platform.dav.common.constant.SysContants;
import com.cloudbroker.bcs.platform.dav.common.util.CacheHelper;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerManager;
import com.cloudbroker.bcs.platform.dav.middle.entity.ChatMsg;
import com.cloudbroker.bcs.platform.dav.middle.entity.ChatRoom;
import com.cloudbroker.bcs.platform.dav.middle.entity.ChatTopic;
import com.cloudbroker.bcs.platform.dav.middle.entity.Customer;
import com.cloudbroker.bcs.platform.dav.middle.entity.CustomerBrokerRel;
import com.cloudbroker.bcs.platform.dav.middle.entity.Tenant;
import com.cloudbroker.bcs.platform.dav.middle.entity.WechatShare;
import com.cloudbroker.bcs.platform.dav.middle.extservice.point.PointAddService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.ChatMsgService;
import com.cloudbroker.bcs.platform.dav.middle.service.ChatRoomService;
import com.cloudbroker.bcs.platform.dav.middle.service.ChatTopicService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerBrokerRelService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.service.PayWaterService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.cloudbroker.bcs.platform.dav.middle.service.WechatShareService;
import com.cloudbroker.bcs.platform.dav.middle.util.point.PointType;

@Service
public class ChatBizServiceImpl implements ChatBizService {
    
    private static final Logger logger = LoggerFactory.getLogger(ChatBizServiceImpl.class);
    
    @Resource
    private ChatTopicService chatTopicService;
    
    @Resource
    private ChatRoomService chatRoomService;
    
    @Resource
    private YunxinT2BizService yunxinT2;
    
    @Resource
    private CustomerService customerService;
    
    @Resource
    private BrokerService brokerService;
    
    @Resource
    private BrokerManagerService brokerManagerService;
    
    @Resource
    private CustomerBrokerRelService customerBrokerRelService;
    
    @Resource
    private PayWaterService payWaterService;
    
    @Resource
    private WechatShareService wechatShareService;
    
    @Resource
    private WeixinT2BizService weixinT2;
    
    @Resource
    private ChatMsgService chatMsgService;
    
    @Resource
    private CCLiveT2BizService ccLiveT2BizService;
    
    @Resource
    private TenantService tenantService;
    
    @Resource
    private PointAddService pointAddService;
    
    private static final long NUM = 25;
    
    @Override
    public HSBCPSBackVO funcChattingTopicSet(ChatTopicForm param) {
        ChatTopic ct = new ChatTopic();
        ct.setCreate_by(HSBCPSBizDataContext.getBrokerId());
        ct.setCreate_time(new Date());
        ct.setTopic_title(param.getTopic());
        chatTopicService.save(ct);
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public ChatRoomInfoBackForm funcChatroomInfo(HSBCPSVO param) {
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(HSBCPSBizDataContext.getBrokerId());
        ChatRoomInfoBackForm form = new ChatRoomInfoBackForm();
        if (chatRoom == null) {
            return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, ChatRoomInfoBackForm.class);
        }
        form.setRoom_title(chatRoom.getRoom_title());
        form.setRoom_status(chatRoom.getRoom_status());
        form.setAll_gag_flag(chatRoom.getAll_gag_flag());
        form.setYunxin_room_id(chatRoom.getYunxin_room_id());
        form.setYunxin_broadcast_url(chatRoom.getYunxin_broadcast_url());
        form.setYunxin_room_notice(chatRoom.getYunxin_room_notice());
        form.setLive_broadcast_url(chatRoom.getLive_broadcast_url());
        
        /*前段主体颜色设置*/
        form.setSchemecolor_value(chatRoom.getSchemecolor_value());
        /*设置在线人数开关和阈值*/
        form.setShow_person_num_flag(chatRoom.getShow_person_num_flag());
        form.setShow_person_num_threshold(chatRoom.getShow_person_num_threshold());
        return VOUtil.setSuccessResult(form);
    }
    
    @Override
    public HSBCPSBackVO funcChatroomSet(ChatRoomSetForm param) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
        if (chatRoom == null) {
            chatRoom = new ChatRoom();
        }
        chatRoom.setRoom_status(Integer.valueOf(param.getRoom_status()));
        chatRoom.setRoom_title(param.getRoom_title());
        chatRoom.setYunxin_broadcast_url(param.getYunxin_broadcast_url());
        chatRoom.setYunxin_room_id(param.getYunxin_room_id());
        chatRoom.setYunxin_room_notice(param.getYunxin_room_notice());
        chatRoom.setUpdate_time(new Date());
        if (chatRoom.getChat_room_id() == null) {
            chatRoom.setBroker_id(brokerId);
            chatRoomService.save(chatRoom);
        } else {
            chatRoomService.update(chatRoom);
        }
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public HSBCPSBackVO funcHisChatDel(HisChatDelForm form) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String chat_msg_id = form.getChat_msg_id();
        ChatMsg cm = chatMsgService.get(chat_msg_id);
        if (null == cm || !broker_id.equals(cm.getBroker_id())) {
            return VOUtil.genErrorResultVo(ChatRoomErr.NO_SUCH_CHAT_MSG);
        } else {
            String hisChat = CacheKeys.HIS_CHAT + broker_id;
            String content = cm.getMsg_content();
            CacheHelper.zrem(hisChat, cm.getChat_msg_id(), content);
            chatMsgService.delete(chat_msg_id);
        }
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public HSBCPSBackVO funcSetHisChat(SetHisChatForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        if (StringUtil.isEmpty(param.getTopic())) {
            ChatTopic curTopic = chatTopicService.getTopicTitle(broker_id);
            if (null != curTopic) {
                param.setTopic(curTopic.getTopic_title());
                param.setTopic_id(curTopic.getTopic_id());
            }
        }
        param.setTenant_id(HSBCPSBizDataContext.getTenantId().toString());
        param.setBroker_id(ValueUtil.getString(broker_id));
        /*保存聊天信息*/
        ChatMsg cm = chatMsgService.saveChatMsg(param);
        if (null == cm) {
            cm = new ChatMsg();
        }
        String his_content = param.getContent();
        String hisChat = CacheKeys.HIS_CHAT + broker_id;
        String content = his_content.substring(0, his_content.length() - 1) + ",\"chatMsgId\":\""
                + cm.getChat_msg_id() + "\"}";
        CacheHelper.zadd(hisChat, cm.getChat_msg_id(), content);
        cm.setMsg_content(content);
        chatMsgService.update(cm);
        if (CacheHelper.ttl(hisChat) == -1) {
            CacheHelper.expire(hisChat, getTimesnight() - (int) (System.currentTimeMillis() / 1000));
        }
        SessionHelper.getInstance().addNewMessageNumByBrokerId(broker_id);
        
        Customer customer = HSBCPSBizDataContext.getCustomerNoException();
        if (customer != null) {
            pointAddService.addPoint(customer.getMobile(), PointType.CHAT, customer.getUser_id(),
                    customer.getTenant_id());
        }
        return VOUtil.genSuccessResultVo();
    }
    
    public static int getTimesnight() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (int) (cal.getTimeInMillis() / 1000);
    }
    
    @Override
    public ChatHisBackForm funcGetHisChat(GetCacheChatMsgForm param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String hisChat = CacheKeys.HIS_CHAT + broker_id;
        Long position = StringUtil.isEmpty(param.getPosition_str()) ? CacheHelper.zcard(hisChat) : Long
                .parseLong(param.getPosition_str());
        Long num = ValueUtil.getLong(param.getRequest_num(), NUM);
        ChatHisBackForm form = new ChatHisBackForm();
        if (position == 0) {
            form.setData_list(new ArrayList<String>());
            form.setPosition_str(0L);
        } else {
            Set<String> contentSet = position > num ? CacheHelper.zrange(hisChat, position - num, position - 1)
                    : CacheHelper.zrange(hisChat, 0, position - 1);
            List<String> contents = Arrays.asList(contentSet.toArray(new String[contentSet.size()]));
            form.setData_list(contents);
            form.setPosition_str(position - num > 0 ? position - num : 0);
        }
        return VOUtil.setSuccessResult(form);
    }
    
    @Override
    public ChatMsgPageResult funcPreviewHisChat(GetHisChatMsgForm param) {
        ChatMsgPageResult chatMsgPageResult = new ChatMsgPageResult();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        String topic_id = param.getTopic_id();
        String position_str = param.getPosition_str();
        String topic = param.getTopic_key_word();
        
        Integer request_num = SysContants.DEFAULT_REQUSET_NUM;
        if (!StringUtil.isEmpty(param.getRequest_num())) {
            request_num = Integer.valueOf(param.getRequest_num());
        }
        List<ChatMsg> chatMsgList;
        if (StringUtil.isEmpty(position_str)) {
            //分页查询            
            Integer page_no = SysContants.MIN_REQUEST_NUM;
            if (param.getPage_no() != null) {
                page_no = Integer.parseInt(param.getPage_no());
            }
            Pagination page = new Pagination();
            page.setPage_size(request_num);
            page.setPage_no(page_no);
            /*查询条件*/
            ChatMsg chatMsg = new ChatMsg();
            chatMsg.setBroker_id(broker_id);
            chatMsg.setTenant_id(HSBCPSBizDataContext.getTenantId());
            chatMsg.setStart_time(param.getStart_time());
            chatMsg.setEnd_time(param.getEnd_time());
            chatMsg.setTopic(param.getTopic_key_word());
            chatMsg.setMsg_content(param.getContent_key_word());
            /*排序*/
            SortMarker sm = new SortMarker();
            sm.setField(HSBCPSFields.POSITION_STR);
            sm.setAsc(false);
            chatMsgList = chatMsgService.queryWithPagination(chatMsg, page, sm);
            chatMsgPageResult.setTotal_item_num(page.getTotal_item_num());
        } else {
            String start_time = param.getStart_time();
            String end_time = StringUtil.isBlank(start_time) == true ? null : start_time.substring(0, 10)
                    + " 23:59:59";
            //滚动加载
            chatMsgList = chatMsgService.qryHistoryMsgById(broker_id, topic_id, topic, start_time, end_time,
                    position_str, request_num);
        }
        
        List<ChatMsgListData> chatMsgListDataList = new ArrayList<>();
        for (ChatMsg temp : chatMsgList) {
            ChatMsgListData chatMsgListData = new ChatMsgListData();
            chatMsgListData.setChat_msg_id(temp.getChat_msg_id().toString());
            chatMsgListData.setSend_time(temp.getSend_time());
            chatMsgListData.setContent(temp.getMsg_content());
            chatMsgListData.setTopic(temp.getTopic());
            chatMsgListDataList.add(chatMsgListData);
            position_str = temp.getPosition_str();
        }
        chatMsgPageResult.setPosition_str(position_str);
        chatMsgPageResult.setData_list(chatMsgListDataList);
        return VOUtil.setSuccessResult(chatMsgPageResult);
    }
    
    @Override
    public ChatHisBackForm funcExportHisChat(GetCacheChatMsgForm param) {
        return null;
    }
    
    @Override
    public BrokerInfoNologinBackForm queryBrokerInfoNologin(BrokerInfoNologinForm param) {
        String broker_key = param.getBroker_key();
        Broker broker = brokerService.getByKey(broker_key);
        if (null == broker) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, BrokerInfoNologinBackForm.class);
        }
        // 大V信息
        String broker_nickname = broker.getBroker_name();
        BrokerInfoNologinBackForm form = new BrokerInfoNologinBackForm();
        form.setBroker_id(broker.getBroker_id());
        form.setBroker_name(broker_nickname);
        form.setBroker_avatar(broker.getBroker_avatar());
        DataContext.setBrokerId(String.valueOf(broker.getBroker_id()));
        form.setWeixin_appkey(ConfigValues.getWeixinAppKey());
        form.setLoading_img_url(broker.getLoading_img_url());
        if ("0".equals(String.valueOf(broker.getThird_pay_status()))) {
            form.setPay_status("0");
        } else {
            form.setPay_status("1");
        }
        String serviceTel = broker.getService_tel();
        if (StringUtil.isEmpty(serviceTel)) {
            serviceTel = "0571-26695555";
        }
        form.setService_tel(serviceTel);
        Long broker_id = broker.getBroker_id();
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(broker_id);
        String invitation_code = null;
        if (chatRoom != null) {
            form.setSchemecolor_value(ValueUtil.getInt(chatRoom.getSchemecolor_value(), 1));
            form.setHome_page_title(chatRoom.getHome_page_title());
            invitation_code = chatRoom.getInvitation_code();
        }
        if (invitation_code == null || invitation_code.isEmpty()) {
            form.setInvitation_flag(1);
        } else {
            form.setInvitation_flag(0);
        }
        /*前段微信分享信息设置*/
        WechatShare wechatShare = wechatShareService.getWechatShareByBrokerId(broker_id);
        if (wechatShare != null) {
            form.setWechatshare_abstract(wechatShare.getShare_abstract());
            form.setWechatshare_img_url(wechatShare.getImg_url());
            form.setWechatshare_link_url(wechatShare.getLink_url());
            form.setQrcode_url(wechatShare.getQrcode_url());
            form.setWechatshare_title(wechatShare.getShare_title());
        }
        //获取用为行为分析系统key
        String userBehaviorAppKey = ConfigValues.getUserBehaviorAppKey(broker.getBroker_id());
        form.setUser_behavior_app_key(userBehaviorAppKey);
        
        form.setWx_ticket(this.setWxTicket(broker_id));
        form.setWb_clientid(ConfigValues.getWeiboAppKey());
        form.setQq_clientid(ConfigValues.getQQAppKey());
        form.setOss_prefix(ConfigValues.getInterfaceOssAddr());
        return VOUtil.setSuccessResult(form);
    }
    
    private String setWxTicket(Long broker_id) {
        String wxTicket = SessionHelper.getInstance().getWxTicket(broker_id);
        if (StringUtil.isEmpty(wxTicket)) {
            GetTicketForm getTicketForm = new GetTicketForm();
            getTicketForm.setBroker_id(broker_id);
            GetTicketBackVo backVo = weixinT2.getTicket(getTicketForm);
            if (backVo == null) {
                return "";
            }
            wxTicket = ValueUtil.getString(backVo.getTicket());
            SessionHelper.getInstance().setWxTicket(broker_id, wxTicket);
        }
        return wxTicket;
    }
    
    @Override
    public BrokerInfoBackForm queryBrokerInfo(HSBCPSVO param) {
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        Broker broker = brokerService.get(String.valueOf(broker_id));
        if (null == broker) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, BrokerInfoBackForm.class);
        }
        // 大V信息
        String broker_avater = broker.getBroker_avatar();
        String broker_nickname = broker.getBroker_name();
        String broker_profile = broker.getProfile();
        String current_topic = "";
        Long topic_id = null;
        // 当前话题
        ChatTopic topic = chatTopicService.getTopicTitle(broker_id);
        if (null != topic) {
            current_topic = topic.getTopic_title();
            topic_id = topic.getTopic_id();
        }
        BrokerInfoBackForm form = new BrokerInfoBackForm();
        form.setBroker_avatar(broker_avater);
        form.setBroker_name(broker_nickname);
        form.setProfile(broker_profile);
        form.setTopic(current_topic);
        form.setTopic_id(topic_id);
        form.setBroker_id(broker.getBroker_id());
        BrokerManager brokerManager = brokerManagerService.getBrokerManager(broker_id, broker.getTenant_id());
        if (brokerManager != null) {
            form.setUser_id(brokerManager.getUser_id());
        }
        ChatRoom room = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (room != null) {
            form.setRoom_status(room.getRoom_status());
            form.setLive_broadcast_url(room.getLive_broadcast_url());
            form.setLive_broadcast_flag(room.getLive_broadcast_flag());
            form.setCc_room_id(room.getCc_room_id());
        }
        Customer clientData = HSBCPSBizDataContext.getCustomerNoException();
        if (clientData != null) {
            CustomerBrokerRel customerRel = customerBrokerRelService.getByBrokerIdAndCustomerId(broker_id,
                    clientData.getCustomer_id());
            if (customerRel != null) {
                form.setBlock_flag(customerRel.getBlock_flag() == null ? 0 : customerRel.getBlock_flag());
                form.setGag_flag(customerRel.getGag_flag() == null ? 0 : customerRel.getGag_flag());
            }
        }
        
        /*//FIXME 获取视频直播室状态，参数暂时写死，需要修改的
        Integer liveFlag = LiveUtil.getLiveFlag("D75765C32B573EB19C33DC5901307461", "3ED5E098B40A25F3",
                "D9y1iHTUuOnxWJ2Hr2C5IiL6Womwz8uz");
        form.setLive_flag(liveFlag);*/
        return VOUtil.setSuccessResult(form);
    }
    
    @Override
    public HSBCPSBackVO funcUserGag(UserGagForm param) {
        Broker broker = HSBCPSBizDataContext.getBroker();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        BrokerManager manager = brokerManagerService.getByMobile(broker.getMobile());
        if (String.valueOf(ChatType.CHAT_ROOM_ONE.getVal()).equals(param.getChat_type())) {
            return chatRoomGag(param.getCustomer_id(), Integer.valueOf(param.getGag_flag()),
                    manager.getYunxin_acct(), broker_id);
        } else if (String.valueOf(ChatType.PRIVATE.getVal()).equals(param.getChat_type())) {
            //FIXME 暂时没有私信禁言
            return VOUtil.genSuccessBackVo();
        } else if (String.valueOf(ChatType.CHAT_ROOM.getVal()).equals(param.getChat_type())
                || String.valueOf(ChatType.GAG_ALL.getVal()).equals(param.getChat_type())) {
            return chatRoomAllGag(Integer.valueOf(param.getGag_flag()), broker_id,
                    EnumUtil.valOf(Integer.valueOf(param.getChat_type()), ChatType.class));
        }
        return VOUtil.genErrorResultVo(ClientErr.GAG_FAIL);
    }
    
    private HSBCPSBackVO chatRoomAllGag(Integer gagOrCancle, Long broker_id, ChatType type) {
        ChatRoom room = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (room == null) {
            return VOUtil.genErrorResultVo(ChatRoomErr.NO_SUCH_CHAT_ROOM);
        }
        switch (type) {
            case CHAT_ROOM:
                room.setRoom_status(gagOrCancle);
                break;
            case GAG_ALL:
                room.setAll_gag_flag(gagOrCancle);
                break;
            default:
                break;
        }
        chatRoomService.updateCAS(room);
        return VOUtil.setSuccessResult(new HSBCPSBackVO());
    }
    
    /**
     * 聊天室禁言
     * @param fansId
     * @param gagOrCancle
     * @param operator
     * @param broker_id
     * @return
     */
    private HSBCPSBackVO chatRoomGag(String fansId, Integer gagOrCancle, String operator, Long broker_id) {
        ChatRoom queryParam = new ChatRoom();
        queryParam.setBroker_id(broker_id);
        ChatRoom room = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (room == null) {
            // 禁言失败
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.ChatRoomErr.NO_SUCH_CHAT_ROOM);
        }
        String roomid = room.getYunxin_room_id();
        Customer fans = customerService.get(fansId);
        if (fans == null) {
            return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
        }
        /*Map<String, Object> queryparams = new HashMap<String, Object>();
        queryparams.put("customer_id", fans.getCustomer_id());
        queryparams.put("broker_id", broker_id);*/
        CustomerBrokerRel customerBrokerRel = customerBrokerRelService.getByBrokerIdAndCustomerId(broker_id,
                fans.getCustomer_id());
        if (customerBrokerRel == null) {
            return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
        }
        
        SetMemberRoleForm param = new SetMemberRoleForm();
        param.setRoomid(Integer.valueOf(roomid));
        param.setOperator(operator);
        param.setTarget(fans.getYunxin_accid());
        param.setOpt("-2");
        param.setOptvalue(GagType.YES.getVal() == gagOrCancle);
        param.setLevel(2);
        SetMemberRoleBackVo result = yunxinT2.setMemberRole(param);
        Integer resultcode = Integer.valueOf(result.getCode());
        if (resultcode != null && resultcode != 200 && resultcode != 417) {
            logger.error("云信禁言失败：" + resultcode + result.getError_info());
            logger.error(result.toString());
            // 禁言失败
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.ClientErr.GAG_FAIL);
        }
        customerBrokerRel.setGag_flag(gagOrCancle);
        customerBrokerRelService.update(customerBrokerRel);
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public RewardNumBackForm funcRewardNumGet(HSBCPSVO param) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        Map<String, Object> map = new HashMap<>();
        map.put("broker_id", brokerId);
        map.put("date", DateTimeUtil.getCurrentDateString(DateTimeUtil.FORMAT_YYYYMMDD_NO_BREAK));
        map.put("pay_source", PaySource.COMMENT.getVal());
        Integer count = payWaterService.countTodayReward(map);
        RewardNumBackForm form = new RewardNumBackForm();
        form.setReward_num(count);
        return VOUtil.setSuccessResult(form);
    }
    
    @Override
    public HSBCPSBackVO funcSchemeColorSelect(SchemeColorSelectForm param) {
        Long brokerId = ValueUtil.getLong(param.getBroker_id());
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, HSBCPSBackVO.class);
        }
        chatRoom.setSchemecolor_value(param.getSchemecolor_value());
        
        chatRoomService.updateChatroomSchemeColor(chatRoom);
        
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public HSBCPSBackVO funcLiveBroadcastUrlSet(LiveBroadcastUrlForm param) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        if (null == brokerId) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, HSBCPSBackVO.class);
        }
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, HSBCPSBackVO.class);
        }
        chatRoom.setLive_broadcast_url(param.getLive_broadcast_url());
        chatRoom.setLive_broadcast_title(param.getLive_broadcast_title());
        chatRoom.setLive_broadcast_flag(Integer.parseInt(param.getLive_broadcast_flag()));
        
        chatRoomService.updateLiveBoradcastUrl(chatRoom);
        
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public LiveBroadcastUrlDetailResult funcLiveBroadcastUrlGet(HSBCPSVO param) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        if (null == brokerId) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT,
                    LiveBroadcastUrlDetailResult.class);
        }
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, LiveBroadcastUrlDetailResult.class);
        }
        LiveBroadcastUrlDetailResult liveBroadcastUrlDetailResult = new LiveBroadcastUrlDetailResult();
        liveBroadcastUrlDetailResult.setLive_broadcast_title(chatRoom.getLive_broadcast_title());
        liveBroadcastUrlDetailResult.setLive_broadcast_url(chatRoom.getLive_broadcast_url());
        liveBroadcastUrlDetailResult.setLive_broadcast_flag(chatRoom.getLive_broadcast_flag());
        return VOUtil.setSuccessResult(liveBroadcastUrlDetailResult);
    }
    
    @Override
    public SchemeColorValueResult funcSchemeColorUsedGet(HSBCPSVO param) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        if (null == brokerId) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, SchemeColorValueResult.class);
        }
        String schemecolor_value = chatRoomService.getSchemeColorValueByBrokerId(brokerId);
        
        SchemeColorValueResult schemeColorValueResult = new SchemeColorValueResult();
        schemeColorValueResult.setSchemecolor_value(schemecolor_value);
        return VOUtil.setSuccessResult(schemeColorValueResult);
    }
    
    @Override
    public HSBCPSBackNumVO funcNewMessageNum(HSBCPSVO param) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        Integer num = SessionHelper.getInstance().getNewMessageNumByBrokerId(brokerId);
        HSBCPSBackNumVO vo = new HSBCPSBackNumVO();
        vo.setNum(num);
        return VOUtil.setSuccessResult(vo);
    }
    
    @Override
    public HSBCPSBackVO funcClearMessageNum(HSBCPSVO form) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        SessionHelper.getInstance().clearNewMessageNumByBrokerId(brokerId);
        return VOUtil.genSuccessBackVo();
    }
    
    @Override
    public HSBCPSBackVO funcUserBlock(UserBlockForm form) {
        Customer fans = customerService.get(form.getCustomer_id());
        if (fans == null) {
            return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
        }
        CustomerBrokerRel customerBrokerRel = customerBrokerRelService.getByBrokerIdAndCustomerId(
                HSBCPSBizDataContext.getBrokerId(), fans.getCustomer_id());
        if (customerBrokerRel == null) {
            return VOUtil.genErrorResultVo(ClientErr.NO_SUCH_CLIENT);
        }
        if (customerBrokerRel.getBlock_flag().equals(Integer.valueOf(form.getBlock_flag()))) {
            return VOUtil.genErrorResultVo(ClientErr.REPEAT_OPERATION);
        }
        customerBrokerRel.setBlock_flag(Integer.valueOf(form.getBlock_flag()));
        customerBrokerRelService.update(customerBrokerRel);
        return VOUtil.genSuccessResultVo();
    }
    
    @Override
    public ChatTopicListResult funcGetChattingTopicList(ChatTopicListForm form) {
        ChatTopicListResult chatTopicListResult = new ChatTopicListResult();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        Integer tenant_id = HSBCPSBizDataContext.getTenantId();
        String start_time = form.getStart_time();
        String end_time = form.getEnd_time();
        int page_no = Integer.parseInt(form.getPage_no());
        int page_size = Integer.parseInt(form.getPage_count());
        page_no = (page_no - 1) * page_size;
        String topic_keyword = form.getTopic_key_word();
        String content_keyword = form.getContent_key_word();
        List<ChatTopic> chatTopicList = chatMsgService.getTopicList(broker_id, tenant_id, start_time, end_time,
                page_no, page_size, topic_keyword, content_keyword);
        
        List<ChatTopicListData> chatTopicListDatas = new ArrayList<>();
        for (ChatTopic chatTopic : chatTopicList) {
            ChatTopicListData topicListData = new ChatTopicListData();
            int his_chatmsg_num = chatMsgService.countByTopic(chatTopic.getTopic_id(), tenant_id);
            topicListData.setTopic(chatTopic.getTopic_title());
            topicListData.setCreate_time(DateTimeUtil.toString(chatTopic.getCreate_time(),
                    DateTimeUtil.FORMAT_YYYYMMDDHHMMSS));
            topicListData.setHis_chatmsg_num(his_chatmsg_num);
            chatTopicListDatas.add(topicListData);
        }
        chatTopicListResult.setData_list(chatTopicListDatas);
        return VOUtil.setSuccessResult(chatTopicListResult);
    }
    
    /*设置CCLive聊天室ID*/
    @Override
    public HSBCPSBackVO funcSetCCRoomId(CCRoomInfoFrom form) {
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        String cc_room_id = form.getCc_room_id();
        String publish_url = form.getPublish_url();
        ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
        if (chatRoom == null) {
            return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, LiveBroadcastUrlDetailResult.class);
        }
        chatRoomService.setCCLiveRoomId(cc_room_id, publish_url, chatRoom.getChat_room_id());
        return VOUtil.genSuccessResultVo();
    }
    
    /*转发CCLive聊天室请求*/
    @Override
    public CCRoomOperResult funcOperateCCRoom(CCRoomOperInfoForm form) {
        return ccLiveT2BizService.funcOperateCCRoom(form);
    }
    
    @Override
    public TenantInfoResult funcTenantInfoGet(TenantKeyForm form) {
        Tenant tenant = tenantService.getByKey(form.getTenant_key());
        if (tenant == null) {
            return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, TenantInfoResult.class);
        }
        //获取用为行为分析系统key
        String userBehaviorAppKey = ConfigValues.getUserBehaviorAppKeyTenant(tenant.getTenant_id());
        
        TenantInfoResult result = new TenantInfoResult();
        result.setTenant_id(tenant.getTenant_id());
        result.setCompany_id(tenant.getCompany_id());
        result.setWeixin_appkey(ConfigValues.getWxAppKeyByTenant(tenant.getTenant_id()));
        result.setUser_behavior_app_key(userBehaviorAppKey);
        result.setOss_prefix(ConfigValues.getInterfaceOssAddr());
        result.setLoading_img_url(tenant.getLoading_img_url());
        result.setWb_clientid(ConfigValues.getWeiboAppKey());
        if ("0".equals(tenant.getThird_pay_status())) {
            result.setPay_status("0");
        } else {
            result.setPay_status("1");
        }
        String serviceTel = tenant.getService_tel();
        if (StringUtil.isEmpty(serviceTel)) {
            serviceTel = "0571-26695555";
        }
        result.setService_tel(serviceTel);
        GetTicketForm getTicketForm = new GetTicketForm();
        getTicketForm.setTenant_id(String.valueOf(tenant.getTenant_id()));
        String ticket = CacheHelper.getInstance().get(ValueUtil.getString(tenant.getTenant_id()));
        if (!ValueUtil.isEmpty(ticket)) {
            result.setWx_ticket(ticket);
        } else {
            GetTicketBackVo backVo = weixinT2.getTicket(getTicketForm);
            if (backVo == null) {
                result.setWx_ticket("");
            } else {
                CacheHelper.getInstance().set(ValueUtil.getString(tenant.getTenant_id()), backVo.getTicket(), 6000);
                result.setWx_ticket(backVo.getTicket());
            }
        }
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HSBCPSBackVO funcSetCcRoomStatus(CCRoomStatusForm form) {
        HSBCPSBackVO result = new HSBCPSBackVO();
        Integer tenantId = HSBCPSBizDataContext.getTenantId();
        if (tenantId == null) {
            return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, TenantInfoResult.class);
        }
        Long brokerID = HSBCPSBizDataContext.getBrokerId();
        if (brokerID == null) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, TenantInfoResult.class);
        }
        chatRoomService.setCCRoomStatus(brokerID, form.getCc_room_status(), tenantId);
        return VOUtil.setSuccessResult(result);
    }
    
}
